import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { WarehouseGoodsBomService } from './warehouse-goods-bom.service';
import { WarehouseGoodsBasicService } from '../warehouse-goods-basic/warehouse-goods-basic.service'
import { NzMessageService } from 'ng-zorro-antd/message';
@Component({
    selector: 'app-warehouse-goods-bom',
    templateUrl: './warehouse-goods-bom.component.html',
    styleUrls: ['./warehouse-goods-bom.component.scss']
})
export class WarehouseGoodsBomComponent implements OnInit {
    // 列表数据
    @Input() bomList: any = []
    @Input() detailsParams: any = {}
    messageId: any = null
    // 本地缓存数据
    cecheData: any = {}
    // 弹窗显示隐藏
    isVisible: boolean = false

    checked: boolean = false
    // 弹窗查询参数
    modalQueryForm: any = {
        // 当前页
        page: 1,
        // 一页加载10
        pageSize: 10,
    }
    // 弹窗列表数据
    modalTableData: any = {
        // 数据列表集合
        records: [],
        // 总条数
        total: 0
    }
    // 路由数据
    routeParams: any = {}
    // 选中商品的集合
    selectCheckGoodsList: any = []

    constructor(
        private activatedRoute: ActivatedRoute,
        private message: NzMessageService,
        private warehouseGoodsBomService: WarehouseGoodsBomService,
        private warehouseGoodsBasicService: WarehouseGoodsBasicService,
    ) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe((params) => {
            this.routeParams = params
        })
    }
    // 出库数量累加事件
    onBlurCountNum() {
        this.setCountTotal()
    }
    // 出库数量 回车聚焦到下一个
    onKeydownEnter(ev: any, id: number) {
        const { keyCode } = ev
        if (keyCode == 13) {
            document.getElementById(`goodsBomID${id + 1}`)?.focus()
        }
    }
    onDelete(item: any, i: any) {
        this.bomList.splice(i, 1)
        this.selectCheckGoodsList = this.bomList
    }
    // 添加商品
    onAddGoods() {
        this.httpWhList()
        this.selectCheckGoodsList = this.bomList
        this.isVisible = true
    }
    // 保存
    onSave() {
        const { id } = this.routeParams
        if (this.selectCheckGoodsList?.length <= 0) { // 判断进来有修改
            this.selectCheckGoodsList = this.bomList
        }
        // if (this.selectCheckGoodsList?.length <= 0) {
        //     this.message.warning('请选择商品')
        //     return
        // }
        if (this.selectCheckGoodsList.length) {
            for (const item of this.selectCheckGoodsList) {
                const { number } = item
                if (!number) {
                    this.message.warning('请输入数量')
                    return
                }
            }
        }
        const params = {
            id,
            state: this.detailsParams.state,
            bomList: JSON.stringify(this.selectCheckGoodsList)
        }
        this.warehouseGoodsBasicService.update(params).subscribe((res: any) => {
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.createMessage("success", res.message);
        }, err => {
            this.createMessage("error", err.message);
        })

    }
    // 关闭弹窗
    onModalClose() {
        this.isVisible = false
    }
    // 查询商品
    onModalQuery() {
        this.modalTableData.page = 1
        this.httpWhList()
    }
    // 关联已选商品
    onModalRelationGoods() {
        if (this.selectCheckGoodsList?.length == 0) {
            this.createMessage('warning', '请至少选择1件商品');
            return
        }
        this.bomList = this.selectCheckGoodsList
        this.onModalClose()
        this.setCountTotal()
    }
    // 选中全部商品
    onModalAllChecked(check: any) {
        const records = this.modalTableData?.records;
        records.forEach((item: any) => item.checked = check);
        for (let index = 0; index < records.length; index++) {
            const element = records[index];
            this.selectCheckGoodsList = this.selectCheckGoodsList.filter((item: any) => item.id !== element.id)
        }
        for (let index = 0; index < records.length; index++) {
            const { checked, id, name, code, attr } = records[index];
            if (checked) {
                this.selectCheckGoodsList.push({
                    id,
                    // 商品名称
                    name,
                    // 69码
                    code,
                    // 商品规格
                    attr,
                });
            }
        }
    }
    // 选中某种商品
    onModalItemChecked(item: any, check: any) {
        const { id: itemId } = item
        const index = this.modalTableData?.records?.findIndex((item: { id: number; }) => item.id === itemId)
        const element = this.modalTableData?.records?.[index];
        element.checked = check
        const { checked, id, name, code, attr } = element
        if (checked) {
            this.selectCheckGoodsList.push({
                id,
                // 商品名称
                name,
                // 69码
                code,
                // 商品规格
                attr,
            })
        } else {
            this.selectCheckGoodsList = this.selectCheckGoodsList.filter((item: any) => item.id !== id)
        }
        this.updateCheckAll();
    }
    /**
    * 页码改变
    * @param index 页码数
    */
    onModalPageIndexChange(index: Number) {
        this.modalQueryForm.page = index;
        this.httpWhList()
    }
    /**
     * 每页条数改变的回调
     * @param index 页码数
     */
    onModalPageSizeChange(index: Number) {
        this.modalQueryForm.pageSize = index;
        this.httpWhList()
    }
    // 出库数量累加
    setCountTotal() {
        this.cecheData.countTotal = 0
        this.bomList?.forEach((item: any) => {
            const { number } = item
            if (number) {
                this.cecheData.countTotal += ~~number
            }
        });
    }
    // 设置选中
    setChecked(val: any) {
        this.modalTableData?.records?.forEach((element: any) => {
            element.checked = val
        });
    }
    // 判断item是否全部选择
    updateCheckAll() {
        const index = this.modalTableData.records.findIndex((item: { checked: boolean; }) => item.checked == false);
        if (index != -1) {
            this.checked = false;
        } else {
            this.checked = true;
        }
    }
    // 商品列表
    async httpWhList() {
        try {
            const { data }: any = await this.warehouseGoodsBomService.whList(this.modalQueryForm)
            if (data) {
                this.modalTableData = data
                this.setChecked(false)
                this.checked = false
                if (this.selectCheckGoodsList.length != 0) {
                    for (let index = 0; index < this.selectCheckGoodsList.length; index++) {
                        const element = this.selectCheckGoodsList[index];
                        for (let k = 0; k < this.modalTableData.records.length; k++) {
                            const obj = this.modalTableData.records[k];
                            if (element.id == obj.id) {
                                obj.checked = true;
                                continue;
                            }
                        }
                    }
                }
                this.updateCheckAll()
            }
        } catch (error) {

        }
    }
    /**
     * 开启loading
     */
    createBasicMessage(): void {
        this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
    }
    /**
     * 移除loading
     */
    removeBasicMessage() {
        this.message.remove(this.messageId);
        this.messageId = null;
    }
    /**
    * 全局展示操作反馈信息
    * @param type 其他提示类型 success:成功 error:失败 warning:警告
    */
    createMessage(type: any, str: any): void {
        this.message.create(type, str);
    }

}
